<template>
  <div class="p-2">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>{{ isViewMode ? '健康监测详情' : '开始健康监测' }}</span>
          <div class="right-buttons">
            <el-button v-if="currentStep > 0 && !isViewMode" type="primary" plain @click="prevStep">上一步</el-button>
            <el-button v-if="currentStep < steps.length - 1 && !isViewMode" type="primary" @click="nextStep">下一步</el-button>
            <el-button v-if="currentStep === steps.length - 1 && !isViewMode" type="success" @click="submitForm">提交</el-button>
            <el-button @click="cancel">{{ isViewMode ? '返回' : '取消' }}</el-button>
          </div>
        </div>
      </template>

      <!-- 成功提交显示 -->
      <div v-if="showSuccessMessage" class="success-message">
        <el-result icon="success" title="健康监测数据提交成功">
          <template #extra>
            <div class="countdown-container">
              <el-progress
                type="circle"
                :percentage="countdownPercentage"
                :stroke-width="6"
                :width="100"
                status="success"
              >
                <template #default>
                  <div class="countdown-text">
                    <span>{{ countdown }}秒后</span>
                    <span>返回列表</span>
                  </div>
                </template>
              </el-progress>
            </div>
            <div class="mt-4">
              <el-button type="primary" @click="handleReturnToList">立即返回</el-button>
            </div>
          </template>
        </el-result>
      </div>

      <!-- 步骤内容 -->
      <div v-else>
        <!-- 进度条 -->
        <el-progress
          v-if="!isViewMode"
          :percentage="progressPercentage"
          :text-inside="true"
          :stroke-width="20"
          status="success"
          style="margin: 15px 0;"
        />

        <!-- 步骤条 -->
        <el-steps v-if="!isViewMode" :active="currentStep" finish-status="success" class="mb-4">
          <el-step v-for="(step, index) in steps" :key="index" :title="step.title" :description="step.description" />
        </el-steps>

        <!-- 步骤内容区域 -->
        <div class="step-content">
          <!-- 步骤1：基本信息 -->
          <div v-show="currentStep === 0">
            <el-form ref="basicInfoFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="老人姓名" prop="elderName">
                    <el-select
                      v-model="form.elderName"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入老人姓名搜索"
                      :remote-method="searchElders"
                      :loading="searchLoading"
                      style="width: 100%"
                      @change="handleElderChange"
                      :disabled="isViewMode"
                    >
                      <el-option
                        v-for="item in elderOptions"
                        :key="item.elderId"
                        :label="item.elderName"
                        :value="item.elderName"
                      >
                        <div class="flex justify-between">
                          <span>{{ item.elderName }}</span>
                          <span class="text-gray-400">{{ item.roomNumber || '未分配房间' }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="检查日期" prop="checkDate">
                    <el-input
                      v-model="form.checkDate"
                      placeholder="系统自动生成当前日期时间"
                      style="width: 100%"
                      :disabled="true"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="检查人姓名" prop="doctor">
                    <el-input
                      v-model="form.doctor"
                      placeholder="请输入检查人姓名"
                      :disabled="isViewMode || (isNurseUser && !isAdminUser)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="下次检查日期" prop="nextCheckDate">
                    <el-date-picker
                      v-model="form.nextCheckDate"
                      type="datetime"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="请选择下次检查日期"
                      style="width: 100%"
                      :disabled="isViewMode"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 步骤2：身高体重测量 -->
          <div v-show="currentStep === 1">
            <el-form ref="bodyFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="身高(cm)" prop="height">
                    <el-input-number v-model="form.height" :min="0" :max="300" :precision="1" style="width: 100%" @change="calculateBMI" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="体重(kg)" prop="weight">
                    <el-input-number v-model="form.weight" :min="0" :max="500" :precision="1" style="width: 100%" @change="calculateBMI" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="BMI指数" prop="bmi">
                    <el-input-number v-model="form.bmi" :min="0" :max="100" :precision="2" :disabled="true" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-divider>BMI参考范围</el-divider>
              <el-alert
                :title="getBMIStatus(form.bmi)"
                :type="getBMIAlertType(form.bmi)"
                :description="getBMIDescription(form.bmi)"
                show-icon
                :closable="false"
                style="margin-bottom: 20px"
              />
            </el-form>
          </div>

          <!-- 步骤3：血压心率测量 -->
          <div v-show="currentStep === 2">
            <el-form ref="cardiovascularFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="收缩压(mmHg)" prop="bloodPressureHigh">
                    <el-input-number v-model="form.bloodPressureHigh" :min="0" :max="300" :precision="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="舒张压(mmHg)" prop="bloodPressureLow">
                    <el-input-number v-model="form.bloodPressureLow" :min="0" :max="200" :precision="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="脉搏(次/分)" prop="pulse">
                    <el-input-number v-model="form.pulse" :min="0" :max="300" :precision="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="心率(次/分)" prop="heartRate">
                    <el-input-number v-model="form.heartRate" :min="0" :max="300" :precision="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="呼吸频率(次/分)" prop="respiratoryRate">
                    <el-input-number v-model="form.respiratoryRate" :min="0" :max="100" :precision="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="体温(℃)" prop="temperature">
                    <el-input-number v-model="form.temperature" :min="30" :max="45" :precision="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-divider>血压参考范围</el-divider>
              <el-alert
                :title="getBloodPressureStatus(form.bloodPressureHigh, form.bloodPressureLow)"
                :type="getBloodPressureAlertType(form.bloodPressureHigh, form.bloodPressureLow)"
                :description="getBloodPressureDescription(form.bloodPressureHigh, form.bloodPressureLow)"
                show-icon
                :closable="false"
                style="margin-bottom: 20px"
              />
            </el-form>
          </div>

          <!-- 步骤4：血液检查 -->
          <div v-show="currentStep === 3">
            <el-form ref="bloodFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="血糖(mmol/L)" prop="bloodSugar">
                    <el-input-number v-model="form.bloodSugar" :min="0" :max="30" :precision="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="血氧饱和度(%)" prop="bloodOxygen">
                    <el-input-number v-model="form.bloodOxygen" :min="0" :max="100" :precision="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="血脂情况" prop="bloodLipid">
                    <el-input
                      v-model="form.bloodLipid"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入血脂情况，如总胆固醇、低密度脂蛋白、高密度脂蛋白等"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-divider>血糖参考范围</el-divider>
              <el-alert
                :title="getBloodSugarStatus(form.bloodSugar)"
                :type="getBloodSugarAlertType(form.bloodSugar)"
                :description="getBloodSugarDescription(form.bloodSugar)"
                show-icon
                :closable="false"
                style="margin-bottom: 20px"
              />
            </el-form>
          </div>

          <!-- 步骤5：器官功能 -->
          <div v-show="currentStep === 4">
            <el-form ref="organFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="肝功能" prop="liverFunction">
                    <el-input
                      v-model="form.liverFunction"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入肝功能相关指标，如ALT、AST、胆红素等"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="肾功能" prop="kidneyFunction">
                    <el-input
                      v-model="form.kidneyFunction"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入肾功能相关指标，如肌酐、尿素氮等"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 步骤6：健康状态评估 -->
          <div v-show="currentStep === 5">
            <el-form ref="healthStatusFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="健康状态" prop="healthStatus">
                    <el-select v-model="form.healthStatus" placeholder="请选择健康状态" style="width: 100%">
                      <el-option
                        v-for="dict in sys_jkzt"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="异常项目" prop="abnormalItems">
                    <el-input
                      v-model="form.abnormalItems"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入异常项目"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="医疗建议" prop="suggestions">
                    <el-input
                      v-model="form.suggestions"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入医疗建议"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注" prop="remarks">
                    <el-input
                      v-model="form.remarks"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入备注信息"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 步骤7：健康分析结果 -->
          <div v-show="currentStep === 6">
            <div class="health-analysis">
              <div class="analysis-header">
                <h2>健康监测结果分析</h2>
                <p class="subtitle">检查日期: {{ formatDate(form.checkDate) }}</p>
                <p class="subtitle">老人姓名: {{ form.elderName }}</p>
                <p class="subtitle" v-if="form.doctor">检查人: {{ form.doctor }}</p>
              </div>

              <el-divider content-position="left">身体基本指标</el-divider>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>身高</h3>
                    <p class="value">{{ form.height }} cm</p>
                    <p class="status">正常范围: 成人平均身高</p>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>体重</h3>
                    <p class="value">{{ form.weight }} kg</p>
                    <p class="status">按BMI指数评估</p>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>BMI指数</h3>
                    <p class="value" :class="getBMIClass(form.bmi)">{{ form.bmi }}</p>
                    <p class="status">{{ getBMIStatus(form.bmi) }}</p>
                    <p class="description">{{ getBMIDescription(form.bmi) }}</p>
                  </div>
                </el-col>
              </el-row>

              <el-divider content-position="left">血压心率</el-divider>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>血压</h3>
                    <p class="value" :class="getBloodPressureClass(form.bloodPressureHigh, form.bloodPressureLow)">
                      {{ form.bloodPressureHigh }}/{{ form.bloodPressureLow }} mmHg
                    </p>
                    <p class="status">{{ getBloodPressureStatus(form.bloodPressureHigh, form.bloodPressureLow) }}</p>
                    <p class="description">{{ getBloodPressureDescription(form.bloodPressureHigh, form.bloodPressureLow) }}</p>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>心率</h3>
                    <p class="value" :class="getHeartRateClass(form.heartRate)">{{ form.heartRate }} 次/分</p>
                    <p class="status">{{ getHeartRateStatus(form.heartRate) }}</p>
                    <p class="description">正常范围: 60-100次/分</p>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>体温</h3>
                    <p class="value" :class="getTemperatureClass(form.temperature)">{{ form.temperature }} °C</p>
                    <p class="status">{{ getTemperatureStatus(form.temperature) }}</p>
                    <p class="description">正常范围: 36.0-37.2℃</p>
                  </div>
                </el-col>
              </el-row>

              <el-divider content-position="left">血液检查</el-divider>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>血糖</h3>
                    <p class="value" :class="getBloodSugarClass(form.bloodSugar)">{{ form.bloodSugar }} mmol/L</p>
                    <p class="status">{{ getBloodSugarStatus(form.bloodSugar) }}</p>
                    <p class="description">{{ getBloodSugarDescription(form.bloodSugar) }}</p>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="analysis-item">
                    <h3>血氧饱和度</h3>
                    <p class="value" :class="getBloodOxygenClass(form.bloodOxygen)">{{ form.bloodOxygen }} %</p>
                    <p class="status">{{ getBloodOxygenStatus(form.bloodOxygen) }}</p>
                    <p class="description">正常范围: 95%-100%</p>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="analysis-item" v-if="form.respiratoryRate">
                    <h3>呼吸频率</h3>
                    <p class="value">{{ form.respiratoryRate }} 次/分</p>
                    <p class="description">正常范围: 12-20次/分</p>
                  </div>
                </el-col>
              </el-row>

              <el-divider content-position="left">其他检查数据</el-divider>
              <el-row :gutter="20" v-if="form.bloodLipid || form.liverFunction || form.kidneyFunction">
                <el-col :span="24">
                  <div class="analysis-other">
                    <div class="other-item" v-if="form.bloodLipid">
                      <h3>血脂情况</h3>
                      <p>{{ form.bloodLipid }}</p>
                    </div>
                    <div class="other-item" v-if="form.liverFunction">
                      <h3>肝功能</h3>
                      <p>{{ form.liverFunction }}</p>
                    </div>
                    <div class="other-item" v-if="form.kidneyFunction">
                      <h3>肾功能</h3>
                      <p>{{ form.kidneyFunction }}</p>
                    </div>
                  </div>
                </el-col>
              </el-row>

              <el-divider content-position="left">综合评估</el-divider>
              <el-row>
                <el-col :span="24">
                  <div class="analysis-summary">
                    <div class="summary-header">
                      <h3>健康状态</h3>
                      <p class="health-status" :class="getHealthStatusClass(form.healthStatus)">
                        {{ getHealthStatusLabel(form.healthStatus) }}
                      </p>
                    </div>

                    <template v-if="form.abnormalItems">
                      <div class="summary-section">
                        <h3>异常项目</h3>
                        <div class="summary-content">{{ form.abnormalItems }}</div>
                      </div>
                    </template>

                    <template v-if="form.suggestions">
                      <div class="summary-section">
                        <h3>医疗建议</h3>
                        <div class="summary-content">{{ form.suggestions }}</div>
                      </div>
                    </template>

                    <template v-if="form.remarks">
                      <div class="summary-section">
                        <h3>备注</h3>
                        <div class="summary-content">{{ form.remarks }}</div>
                      </div>
                    </template>

                    <div class="summary-section">
                      <h3>下次检查时间</h3>
                      <div class="summary-content">{{ formatDate(form.nextCheckDate) }}</div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="HealthCheckStepInput" lang="ts">
import { listHealthCheck, getHealthCheck, addHealthCheck, updateHealthCheck } from '@/api/nursing/healthCheck';
import { listElderBasic } from '@/api/nursing/elderBasic';
import { HealthCheckVO, HealthCheckForm } from '@/api/nursing/healthCheck/types';
import { ElderBasicVO } from '@/api/nursing/elderBasic/types';
import { getCurrentInstance, computed, ref, reactive, onMounted, onUnmounted } from 'vue';
import type { FormRules, FormInstance } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_jkzt } = toRefs<any>(proxy?.useDict('sys_jkzt'));
const router = useRouter();
const route = useRoute();
const userStore = useUserStoreHook();

// 倒计时变量
const countdown = ref(5); // 5秒倒计时
const showSuccessMessage = ref(false);
let countdownTimer: number | null = null;

// 查看模式标志
const isViewMode = computed(() => route.query.mode === 'view');

// 用户角色判断
const isNurseUser = computed(() => userStore.roles.some(role => role === 'nursing'));
const isAdminUser = computed(() => userStore.roles.some(role => role === 'admin_ms' || role === 'admin'));

// 健康监测数据
const form = ref<HealthCheckForm & { elderId?: number }>({
  id: undefined,
  elderName: undefined,
  checkDate: (() => {
    // 直接使用本地时间并格式化为字符串
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    // 返回格式化的时间字符串 YYYY-MM-DD HH:mm:ss
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  })(),
  height: undefined,
  weight: undefined,
  bmi: undefined,
  bloodPressureHigh: undefined,
  bloodPressureLow: undefined,
  pulse: undefined,
  bloodSugar: undefined,
  bloodOxygen: undefined,
  temperature: undefined,
  heartRate: undefined,
  respiratoryRate: undefined,
  bloodLipid: undefined,
  liverFunction: undefined,
  kidneyFunction: undefined,
  healthStatus: undefined,
  abnormalItems: undefined,
  doctor: undefined,
  suggestions: undefined,
  nextCheckDate: undefined,
  remarks: undefined,
  elderId: undefined,
});

// 表单验证规则
const rules = reactive<FormRules>({
  elderName: [{ required: true, message: '请选择老人', trigger: 'change' }],
  checkDate: [{ required: true, message: '请选择检查日期', trigger: 'change' }],
  doctor: [{ required: true, message: '请输入检查人姓名', trigger: 'blur' }],
  height: [{ required: true, message: '请输入身高', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入体重', trigger: 'blur' }],
  bloodPressureHigh: [{ required: true, message: '请输入收缩压', trigger: 'blur' }],
  bloodPressureLow: [{ required: true, message: '请输入舒张压', trigger: 'blur' }],
  temperature: [{ required: true, message: '请输入体温', trigger: 'blur' }],
  healthStatus: [{ required: true, message: '请选择健康状态', trigger: 'change' }],
});

// 老人选项
const elderOptions = ref<ElderBasicVO[]>([]);
const searchLoading = ref(false);

// 步骤选项
const steps = [
  { title: '基本信息', description: '老人基本信息与检查信息' },
  { title: '身高体重', description: '身高、体重和BMI指数' },
  { title: '血压心率', description: '血压、心率和体温' },
  { title: '血液检查', description: '血糖、血氧和血脂' },
  { title: '器官功能', description: '肝功能和肾功能' },
  { title: '健康评估', description: '健康状态和医疗建议' },
  { title: '分析结果', description: '健康监测结果分析' }
];

// 当前步骤
const currentStep = ref(isViewMode.value ? 6 : 0); // 查看模式直接显示分析结果页
const progressPercentage = computed(() => {
  return Math.round(((currentStep.value + 1) / steps.length) * 100);
});

// 表单引用
const basicInfoFormRef = ref<FormInstance>();
const bodyFormRef = ref<FormInstance>();
const cardiovascularFormRef = ref<FormInstance>();
const bloodFormRef = ref<FormInstance>();
const organFormRef = ref<FormInstance>();
const healthStatusFormRef = ref<FormInstance>();

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 下一步
const nextStep = async () => {
  let isValid = false;

  // 根据当前步骤验证表单
  switch (currentStep.value) {
    case 0: // 基本信息
      await basicInfoFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    case 1: // 身高体重
      await bodyFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    case 2: // 血压心率
      await cardiovascularFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    case 3: // 血液检查
      await bloodFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    case 4: // 器官功能
      await organFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    case 5: // 健康评估
      await healthStatusFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    default:
      isValid = true;
  }

  if (isValid && currentStep.value < steps.length - 1) {
    currentStep.value++;
  } else if (!isValid) {
    proxy?.$modal.msgError('请完成必填项');
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 查看模式下不允许提交
    if (isViewMode.value) {
      return;
    }

    // 根据ID判断是添加还是更新
    if (form.value.id) {
      await updateHealthCheck(form.value);
      proxy?.$modal.msgSuccess('更新成功');
    } else {
      await addHealthCheck(form.value);
      proxy?.$modal.msgSuccess('添加成功');
    }

    // 显示成功信息并开始倒计时
    startCountdown();
  } catch (error) {
    console.error('提交失败', error);
    proxy?.$modal.msgError('提交失败：' + (error instanceof Error ? error.message : String(error)));
    showSuccessMessage.value = false; // 确保失败时不显示成功视图
  }
};

// 取消操作
const cancel = () => {
  try {
    // 直接返回列表页面，无需确认
    window.location.href = '/elder_service/healthCheck';
  } catch (error) {
    console.error('导航跳转失败', error);
  }
};

// 搜索老人
const searchElders = async (query: string = '') => {
  searchLoading.value = true;

  try {
    // 如果没有查询参数，则获取默认列表
    const res = await listElderBasic({
      pageNum: 1,
      pageSize: 20,
      elderName: query,
      reviewStatus: '1' // 只查询审核通过的老人
    });
    console.log('获取老人列表成功', res.rows);
    elderOptions.value = res.rows;
  } catch (error) {
    console.error('搜索老人失败', error);
  } finally {
    searchLoading.value = false;
  }
};

// 初始化检查人姓名
const initDoctorName = () => {
  // 如果是护理员用户，自动填入当前用户昵称
  if (isNurseUser.value && !isAdminUser.value && !form.value.doctor) {
    form.value.doctor = userStore.nickname;
  }
};

// 老人变更事件
const handleElderChange = (value: string) => {
  console.log('老人变更:', value);
  const selectedElder = elderOptions.value.find(item => item.elderName === value);
  if (selectedElder) {
    console.log('选中老人信息:', selectedElder);
    form.value.elderId = Number(selectedElder.elderId);
    // 可以补充额外的老人信息回显逻辑
  }
};

// 计算BMI
const calculateBMI = () => {
  if (form.value.height && form.value.weight) {
    const heightInMeters = form.value.height / 100;
    form.value.bmi = +(form.value.weight / (heightInMeters * heightInMeters)).toFixed(2);
  }
};

// BMI状态判断
const getBMIStatus = (bmi: number | undefined) => {
  if (!bmi) return '未知';
  if (bmi < 18.5) return '体重过轻';
  if (bmi < 24.0) return '正常范围';
  if (bmi < 28.0) return '超重';
  if (bmi < 30.0) return '轻度肥胖';
  if (bmi < 35.0) return '中度肥胖';
  return '重度肥胖';
};

const getBMIAlertType = (bmi: number | undefined) => {
  if (!bmi) return 'info';
  if (bmi < 18.5) return 'warning';
  if (bmi < 24.0) return 'success';
  if (bmi < 28.0) return 'warning';
  return 'error';
};

const getBMIDescription = (bmi: number | undefined) => {
  if (!bmi) return '请输入身高和体重计算BMI';
  if (bmi < 18.5) return '体重过轻可能与营养不良相关，应加强营养摄入';
  if (bmi < 24.0) return '体重在正常范围内，继续保持良好的生活习惯';
  if (bmi < 28.0) return '体重超重，建议控制饮食并增加适度运动';
  if (bmi < 30.0) return '轻度肥胖，需要关注饮食结构并增加运动量';
  if (bmi < 35.0) return '中度肥胖，应在专业指导下制定减重计划';
  return '重度肥胖，存在较高健康风险，需要专业医疗干预';
};

const getBMIClass = (bmi: number | undefined) => {
  if (!bmi) return '';
  if (bmi < 18.5) return 'text-warning';
  if (bmi < 24.0) return 'text-success';
  if (bmi < 28.0) return 'text-warning';
  return 'text-danger';
};

// 血压状态判断
const getBloodPressureStatus = (high: number | undefined, low: number | undefined) => {
  if (!high || !low) return '未知';
  if (high < 90 || low < 60) return '低血压';
  if (high < 120 && low < 80) return '理想血压';
  if (high < 130 && low < 85) return '正常血压';
  if (high < 140 && low < 90) return '正常高值';
  if (high < 160 && low < 100) return '1级高血压';
  if (high < 180 && low < 110) return '2级高血压';
  return '3级高血压';
};

const getBloodPressureAlertType = (high: number | undefined, low: number | undefined) => {
  if (!high || !low) return 'info';
  if (high < 90 || low < 60) return 'warning';
  if (high < 120 && low < 80) return 'success';
  if (high < 130 && low < 85) return 'success';
  if (high < 140 && low < 90) return 'warning';
  return 'error';
};

const getBloodPressureDescription = (high: number | undefined, low: number | undefined) => {
  if (!high || !low) return '请输入收缩压和舒张压';
  if (high < 90 || low < 60) return '血压偏低，可能出现头晕、乏力等症状';
  if (high < 120 && low < 80) return '血压理想，继续保持良好的生活习惯';
  if (high < 130 && low < 85) return '血压正常，保持健康生活方式';
  if (high < 140 && low < 90) return '血压属于正常高值，建议定期监测';
  if (high < 160 && low < 100) return '轻度高血压，需要关注生活方式调整';
  if (high < 180 && low < 110) return '中度高血压，建议在医生指导下用药';
  return '重度高血压，需要积极治疗并密切监测';
};

const getBloodPressureClass = (high: number | undefined, low: number | undefined) => {
  if (!high || !low) return '';
  if (high < 90 || low < 60) return 'text-warning';
  if (high < 130 && low < 85) return 'text-success';
  if (high < 140 && low < 90) return 'text-warning';
  return 'text-danger';
};

// 心率状态判断
const getHeartRateStatus = (rate: number | undefined) => {
  if (!rate) return '未知';
  if (rate < 60) return '心动过缓';
  if (rate <= 100) return '正常范围';
  return '心动过速';
};

const getHeartRateClass = (rate: number | undefined) => {
  if (!rate) return '';
  if (rate < 60) return 'text-warning';
  if (rate <= 100) return 'text-success';
  return 'text-danger';
};

// 体温状态判断
const getTemperatureStatus = (temp: number | undefined) => {
  if (!temp) return '未知';
  if (temp < 36) return '体温偏低';
  if (temp <= 37.2) return '正常体温';
  if (temp <= 38) return '低热';
  if (temp <= 39) return '中热';
  return '高热';
};

const getTemperatureClass = (temp: number | undefined) => {
  if (!temp) return '';
  if (temp < 36) return 'text-warning';
  if (temp <= 37.2) return 'text-success';
  if (temp <= 38) return 'text-warning';
  return 'text-danger';
};

// 血糖状态判断
const getBloodSugarStatus = (sugar: number | undefined) => {
  if (!sugar) return '未知';
  if (sugar < 3.9) return '低血糖';
  if (sugar <= 6.1) return '正常血糖';
  if (sugar <= 7.0) return '血糖偏高';
  return '高血糖';
};

const getBloodSugarAlertType = (sugar: number | undefined) => {
  if (!sugar) return 'info';
  if (sugar < 3.9) return 'warning';
  if (sugar <= 6.1) return 'success';
  if (sugar <= 7.0) return 'warning';
  return 'error';
};

const getBloodSugarDescription = (sugar: number | undefined) => {
  if (!sugar) return '请输入血糖值';
  if (sugar < 3.9) return '血糖偏低，注意补充糖分';
  if (sugar <= 6.1) return '血糖正常，继续保持良好饮食习惯';
  if (sugar <= 7.0) return '血糖偏高，建议控制碳水化合物摄入';
  return '血糖较高，需要关注饮食控制并定期监测';
};

const getBloodSugarClass = (sugar: number | undefined) => {
  if (!sugar) return '';
  if (sugar < 3.9) return 'text-warning';
  if (sugar <= 6.1) return 'text-success';
  if (sugar <= 7.0) return 'text-warning';
  return 'text-danger';
};

// 血氧状态判断
const getBloodOxygenStatus = (oxygen: number | undefined) => {
  if (!oxygen) return '未知';
  if (oxygen < 90) return '严重缺氧';
  if (oxygen < 94) return '轻度缺氧';
  return '正常范围';
};

const getBloodOxygenClass = (oxygen: number | undefined) => {
  if (!oxygen) return '';
  if (oxygen < 90) return 'text-danger';
  if (oxygen < 94) return 'text-warning';
  return 'text-success';
};

// 健康状态判断
const getHealthStatusLabel = (status: string | undefined) => {
  if (!status) return '未评估';
  const dict = sys_jkzt.value.find((item: any) => item.value === status);
  return dict ? dict.label : '未知';
};

const getHealthStatusClass = (status: string | undefined) => {
  if (!status) return '';
  if (status === '1') return 'text-success';
  if (status === '2') return 'text-success';
  if (status === '3') return 'text-warning';
  if (status === '4') return 'text-danger';
  return '';
};

// 日期格式化
const formatDate = (date: string | undefined) => {
  if (!date) return '未设置';
  return date.split(' ')[0];
};

// 检查是否为编辑模式
const checkEditMode = async () => {
  const id = route.query.id;
  if (id) {
    try {
      const res = await getHealthCheck(id as string);
      Object.assign(form.value, res.data);
    } catch (error) {
      console.error('获取健康监测数据失败', error);
      proxy?.$modal.msgError('获取数据失败');
    }
  }
};

// 组件挂载时初始化
onMounted(() => {
  checkEditMode();
  initDoctorName();
  // 加载老人列表，确保下拉选择框有数据
  searchElders('');
});

// 组件卸载时清理资源
onUnmounted(() => {
  console.log('组件卸载，清理定时器');
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});

const clearTimerAndNavigate = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  // 导航到列表页面
  router.push('/elder_service/healthCheck');
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 5; // 重置倒计时为5秒
  showSuccessMessage.value = true; // 显示成功视图

  // 清除已存在的定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }

  countdownTimer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearTimerAndNavigate(); // 倒计时结束时导航
    }
  }, 1000); // 每秒减少1
};

// 计算倒计时进度百分比
const countdownPercentage = computed(() => {
  // 避免除以零并处理初始状态
  if (countdown.value <= 0) return 0;
  return (countdown.value / 5) * 100;
});

// 手动返回列表的处理函数
const handleReturnToList = () => {
  clearTimerAndNavigate();
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.step-content {
  min-height: 350px;
  margin-top: 20px;
}

.health-analysis {
  padding: 20px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.analysis-header {
  text-align: center;
  margin-bottom: 20px;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.analysis-header h2 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409EFF;
}

.subtitle {
  color: #6c757d;
  margin: 5px 0;
  font-size: 16px;
}

.analysis-item {
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  text-align: center;
  margin-bottom: 15px;
  height: 100%;
  min-height: 180px;
  display: flex;
  flex-direction: column;
}

.analysis-item h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.analysis-item .value {
  font-size: 28px;
  font-weight: bold;
  margin: 15px 0;
}

.analysis-item .status {
  color: #606266;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.analysis-item .description {
  color: #909399;
  font-size: 14px;
  margin-top: auto;
}

.analysis-other {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  margin-bottom: 15px;
}

.other-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.other-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.other-item h3 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

.analysis-summary {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.summary-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.summary-header h3 {
  font-size: 18px;
  margin-right: 15px;
  margin-bottom: 0;
  color: #606266;
  min-width: 100px;
}

.summary-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-wrap: wrap;
}

.summary-section h3 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
  min-width: 100px;
}

.summary-content {
  flex: 1;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  min-height: 40px;
}

.health-status {
  font-size: 20px;
  font-weight: bold;
  padding: 8px 15px;
  border-radius: 4px;
  display: inline-block;
  background-color: #f8f9fa;
}

.mt-4 {
  margin-top: 20px;
}

.success-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
}

.countdown-container {
  margin-top: 20px;
}

.countdown-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 14px;
  line-height: 1.2;
}

.el-divider--horizontal {
  margin: 24px 0;
}

.el-divider__text {
  font-size: 18px;
  font-weight: 500;
  color: #409EFF;
}
</style>